// pages/shopping-cart/shopping-cart.js
const util = require('../../utils/util.js');
import api from '../../utils/request/api'
import {
  getCartDetailList, userCenter 
} from '../../utils/request/apiurl'

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		isRequest: false,
		searchGood: {
			page: 1,
			size: 20,
			pages: 0 //总页数
		},
		allsel: false, //全选 
		adminShow: false, //管理      
		shopcarData:[],//购物车数据   
		selectCarShop:[],//选择购物车商品
		total: 0, //总金额        
		selarr: [], //选择的货物      
		hintText: '', //提示的内容      
		hintShow: false ,//是否显示提示 
		uid:null,
		listId:[],//购物车数据id
		isRealname:0,//实名
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		if(wx.getStorageSync('userInfo')!=''){
			var userInfo = wx.getStorageSync('userInfo');
			this.setData({
				uid:userInfo.uid,
				isRealname:userInfo.isRealname
			})
			// this.carList();
		}
		
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		// console.log(this.data.selectCarShop,'this.data.selectCarShopthis.data.selectCarShop')

		if(wx.getStorageSync('userInfo')!=''){
      this.getData()
			this.judgmentAll();
			var userInfo = wx.getStorageSync('userInfo');
			this.setData({
				uid:userInfo.uid,
				isRealname:userInfo.isRealname
			})      
			this.setData({
				searchGood: {
					page: 1,
					size: 20,
					pages: 0 //总页数
				},
				total:0,
				allsel:false
			})
			this.carList();
		}
		console.log()
		 // this.carList();
	},
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},
  //获取用户信息
  getData() {
    var source = {
      uid: this.data.uid || wx.getStorageSync('userInfo').uid
    }
    api.post(userCenter.userData, source).then(res => {
      if (res.status===0){
        var userInfo = wx.getStorageSync('userInfo')
        userInfo['isColonel'] = res.isColonel;
        userInfo['isRealname'] = res.isRealname;
        userInfo['isPayPassword'] = res.isPayPassword;
        userInfo['isColonel'] = res.isColonel //0不是团长，1是团长
				userInfo['role'] = res.role; //0不是快递员，1是快递员
				userInfo['phone'] = res.phone;
        wx.setStorageSync('userInfo', userInfo);
        this.setData({
          uid: res.uid,
          isRealname: res.isRealname
        })
        console.log(wx.getStorageSync('userInfo'))
      }
      
     
    }).catch(err => {
      // wx.showToast({
      // 	title: '暂未登录，请前去登录',
      // 	icon: 'none',
      // 	duration: 2000
      // })
    })
  },
	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {
		wx.showNavigationBarLoading() //在标题栏中显示加载
		this.setData({
			shopcarData:[],
			searchGood: {
				page: 1,
				size: 20,
				pages:0
			},
		})
		this.carList();
		setTimeout(function() {
			wx.hideNavigationBarLoading() //完成停止加载
			wx.stopPullDownRefresh() //停止下拉刷新
		}, 1500);
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {
		// console.log(this.data.isRequest,this.data.searchGood.page,this.data.searchGood.pages)
		if (!this.data.isRequest && this.data.searchGood.page < this.data.searchGood.pages) {
			// console.log('2222')
			this.setData({
				searchGood: {
					page: this.data.searchGood.page + 1,
					size: 20,
					pages: this.data.searchGood.pages
				}
			})
			// console.log(this.data.searchGood)
			this.carList(1)
		}
	},

	/**
	 * 用户点击右上角分享
	 */
// 	onShareAppMessage: function() {
// 
// 	},
	// 购物车列表
	carList(changeType){
		// this.setData({
		// 	isRequest: true
		// })
		var source = {
			uid: this.data.uid,
			page: this.data.searchGood.page,
			size: this.data.searchGood.size,
		}
		var allselData=false
		var total=0
		api.post(getCartDetailList.list, source).then(res => {
			var shopcarData=res.rows
			// debugger
			if(changeType==1){
				this.setData({
				  shopcarData: [...this.data.shopcarData, ...shopcarData],
				})
			}else{
				this.setData({
					shopcarData:shopcarData,
				})
			}
			shopcarData=this.data.shopcarData
			for(var i=0;i<shopcarData.length;i++){
				shopcarData[i]['check']=false	
				this.data.selectCarShop.forEach(v=>{
					if(shopcarData[i].id==v.id){
						// console.log(shopcarData[i].id,v.id,'shopcarData[i].id==v.id')
						 shopcarData[i]['check']=true;
             //修改需求  这里展示现价不展示打折后的价格
            total += shopcarData[i].goodsCount * shopcarData[i].goodsPrice;
            // total += shopcarData[i].goodsCount * shopcarData[i].currentPrice;
					}
				})
				// debugger
				var  skuList=[]
				// var dataList=shopcarData[i].sku
				var goodsSku=JSON.parse(shopcarData[i].sku)
				var skudata=''
				for(var obj in goodsSku){
					if(skudata==''){
						skudata=goodsSku[obj]
					}else{
						skudata=skudata+'/'+goodsSku[obj]
					}
				}
				skuList.push(skudata)
				shopcarData[i]['skuList']=skuList
			}
			
			let pages=res.total/this.data.searchGood.size
			this.setData({
			  searchGood: {
			    page: this.data.searchGood.page,
			    size: this.data.searchGood.size,
			    pages: pages
			  },
			  total:total
			})
			// console.log(res.rows.length,shopcarData.length,this.data.selectCarShop.length,'falsefalse')
			if(shopcarData.length!=0&&shopcarData.length==this.data.selectCarShop.length){
				allselData=true
			}else{
				allselData=false
			}
			// console.log(allselData)
			this.setData({
				shopcarData:this.data.shopcarData,
				allsel:allselData
			})
      //确认添加购物车check默认为true
      //判断缓存的商品idgoodsId是否等于购物车goodsId == 默认true
      //得到缓存
      var shopIdObj = wx.getStorageSync('shopObj');
      var shopId = Number(shopIdObj.shopId);
      if (shopId === undefined || shopId === null){
        return
      }
      //循环
      for (let i in this.data.shopcarData) {
        // let item = 'shopcarData[' + i + '].check'
        let item = "shopcarData["+ i + "].check"
        if (shopId == this.data.shopcarData[i].goodsId){
          //赋值check= true
          // this.setData({
          //   [item]:true
          // })
          //调用一次计算价格
          this.checkTap(i);
        }
      }
      console.log("购物车数据", this.data.shopcarData)
			
		}).catch(err => {
			// console.log(err)
			// wx.showToast({
			// 	title: err.message,
			// 	icon: 'none'
			// })
		})
		// this.setData({
		// 	isRequest: true
		// })
	},
	
	//点击全选  
	allcheckTap: function() {
		let shopcar = this.data.shopcarData,
			allsel = !this.data.allsel, //点击全选后allsel变化
			total = this.data.total;
			total=0;
			var list =[],data=[]
			for (let i = 0, len = shopcar.length; i < len; i++) {
				
				// if(shopcar[i].goodsCount>shopcar[i].repertory){
				// 	wx.showToast({
				// 		title: '库存不足',
				// 		icon: 'none'
				// 	})
				// 	console.log(shopcar[i].check)
				// 	shopcar[i].check=!allsel;
				// 	return false
				// }
					shopcar[i].check = allsel; //所有商品的选中状态和allsel值一样
				
				if (allsel) {
					//如果为选中状态则计算商品的价格		
          //修改需求  这里展示现价不展示打折后的价格
					total +=parseFloat(shopcar[i].goodsPrice * shopcar[i].goodsCount) ;
          // total += parseFloat(shopcar[i].currentPrice * shopcar[i].goodsCount) ;
					data.push(shopcar[i].id)
					list.push(shopcar[i])
				}else{
					total=0;
				}
			}
			// this.data.selarr = allsel ? shopcar : []; //如果选中状态为true那么所有商品为选中状态，将物品加入选中变量，否则为空    
			this.setData({
				allsel: allsel,
				shopcarData: shopcar,
				total:total,
				selarr: this.data.selarr,
				listId:data,
				selectCarShop:list
			});

	},

	//点击单个选择按钮  
	checkTap: function(e) {
		// let Index = e.currentTarget.dataset.index,
    var Index;
    if(e.currentTarget){
      Index = e.currentTarget.dataset.index
    }else{
      Index = e
    }
    console.log("调用了",e,Index,this.data.shopcarData)
		let	shopcar = this.data.shopcarData;
		let	total = this.data.total;
		let	selarr = this.data.selarr;//选择购买的商品
			// console.log(shopcar[Index].check)
    shopcar[Index].check = !shopcar[Index].check || false;
    // shopcar[Index].check = !shopcar[Index].check || false;//111111
		if (shopcar[Index].check) {			//选中
			if(shopcar[Index].id){
				shopcar[Index].check=true;
			// console.log(arr)
			}
			if(shopcar[Index].goodsCount>shopcar[Index].repertory){
				wx.showToast({
					title: '库存不足',
					icon: 'none'
				})
				shopcar[Index].check=false;
				return false
			}else{
				shopcar[Index].check=true;
			}
          //修改需求  这里展示现价不展示打折后的价格
      total += shopcar[Index].goodsCount * shopcar[Index].goodsPrice;
      // total += shopcar[Index].goodsCount * shopcar[Index].currentPrice;
			
    } else {//取消选中
          //修改需求  这里展示现价不展示打折后的价格
      total = total - shopcar[Index].goodsCount * shopcar[Index].goodsPrice;
      // total = total - shopcar[Index].goodsCount * shopcar[Index].currentPrice;	
			// for (let i = 0, len = selarr.length; i < len; i++) {
			// 	if (selarr[i].id===shopcar[Index].id ) {
			// 		selarr[i].check=false				
			// 	}
			// }			
		}
		
		this.setData({
			shopcarData: shopcar,
			total: total,
			selarr: selarr,			
		});
		this.judgmentAll(); //每次按钮点击后都判断是否满足全选的条件  
	},
	//判断是否为全选  
	judgmentAll: function() {
		let shopcar = this.data.shopcarData,
			lenIndex = 0; //选中的物品的个数  
			var list=[],data=[]
		for (let i = 0; i < shopcar.length; i++) { //计算购物车选中的商品的个数    
			// shopcar[i].check && lenIndex++;
			if(shopcar[i].check){
				// console.log(shopcar[i].goodsCount<=shopcar[i].repertory,'1111')
				// if(shopcar[i].goodsCount<=shopcar[i].repertory-1){
					lenIndex++;
					data.push(shopcar[i].id)
					list.push(shopcar[i])
				// }
				
			}	
		}
		this.setData({
			allsel: lenIndex == shopcar.length ,//如果购物车选中的个数和购物车里货物的总数相同，则为全选，反之为未全选
			listId:data,
			selectCarShop:list
		});
	},
	//点击加减按钮  
	numchangeTap: function(e) {
    var that = this;
    //改变购物车之后赋值缓存值,首页重加载列表
    wx.setStorageSync('isLogin', true)
		// console.log(e)
		let Index = e.currentTarget.dataset.index, //点击的商品下标值        
      shopcar = that.data.shopcarData,
			types = e.currentTarget.dataset.types, //是加号还是减号        
      total = that.data.total; //总计    
			var source={
			}
			if(types == 'add'){
				// console.log(shopcar[Index].goodsCount)
				// console.log(shopcar[Index].repertory)
				if(shopcar[Index].goodsCount>shopcar[Index].repertory-1){
					wx.showToast({
						title: '库存不足',
						icon: 'none'
					})
					return false
				}else{
					shopcar[Index].goodsCount++; //对应商品的数量+1
				}
        if (shopcar[Index].check) {
          //修改需求  这里展示现价不展示打折后的价格
          total += parseFloat(shopcar[Index].goodsPrice); //如果商品为选中的，则合计价格+商品单价
          // total += parseFloat(shopcar[Index].currentPrice); //如果商品为选中的，则合计价格+商品单价
				}
				source['cid']=shopcar[Index].id;
				if(shopcar[Index].repertory==0){
					source['count']=shopcar[Index].repertory
				}else{
					source['count']=shopcar[Index].goodsCount
				}
				
			}else if(types == 'minus'){
				// console.log(shopcar[Index].goodNum)
				if(shopcar[Index].goodsCount>1){
					shopcar[Index].goodsCount--; //对应商品的数量-1
          if (shopcar[Index].check) {
          //修改需求  这里展示现价不展示打折后的价格
            total -= parseFloat(shopcar[Index].goodsPrice); //如果商品为选中的，则合计价格-商品单价
            // total -= parseFloat(shopcar[Index].currentPrice); //如果商品为选中的，则合计价格-商品单价
					}
					source['cid']=shopcar[Index].id;
					source['count']=shopcar[Index].goodsCount
				}else{
					wx.showToast({
						title:'不能再减少了',
						icon: 'none'
					})
					return false
				}	
			}
			// if(source.count==0){
			// 	wx.showToast({
			// 		title:'库存不足，请重新选择商品',
			// 		icon: 'none'
			// 	})
			// 	return false
			// }
		api.post(getCartDetailList.update, source).then(res => {	
		}).catch(err => {
			// console.log(err)
			wx.showToast({
				title: err.message,
        icon: 'none',
        success: function () {
          setTimeout(function () {
            //重加载购物车列表
            console.log("重加载")
            that.carList();
          }, 1000);
        }
			})
		})				
    that.setData({
			shopcarData: shopcar,
			total:total
		});
		// console.log(this.data.total)
	},
	//点击移除商品  
	deleteshopTap: function() {		
		if(this.data.listId.length>0){
			var source={
				listId:this.data.listId,	
			}
			api.post(getCartDetailList.del, source).then(res =>{

        //删除购物车之后赋值缓存值,首页重加载列表
        wx.setStorageSync('isLogin', true)
        // if (status == 0){
					wx.showToast({
						title: '成功删除',
						icon: 'none',
						duration:2000,
					})
					this.setData({
					adminShow:false	
					})
					this.carList();
					
				// }else{
        //   wx.showToast({
        //     title: '删除失败',
        //     icon: 'none',
        //     duration: 2000,
        //   })
        // }
			}).catch(err => {
				console.log("失败")
				wx.showToast({
					title: err.message,
					icon: 'none'
				})
			})
		}else{
			wx.showToast({
				title: '未选择需要删除的删除商品',
				icon: 'none',
				duration:2000,
			})
		}
	},
	//点击管理按钮，是否显示管理的选项  
	adminTap: function() {
		this.setData({
			adminShow: !this.data.adminShow
		});
	},
// 跳转结算
goclearingTap(){ 
  console.log(this.data.isRealname)
	if(this.data.isRealname==1){
		let shopcar = this.data.shopcarData;
		var num1=0;
		var num2=0
		var num3=0
		// shopcar.for
		for(let i=0 ;i<shopcar.length;i++){
			// console.log(this.data.listId)
			// console.log(shopcar[i].check)
			if(shopcar[i].check){	
				// console.log(shopcar[i])
				num1++
				// console.log(num1,'num1')
				if(shopcar[i].repertory >= shopcar[i].goodsCount){
					num3++
					// console.log(num3,'num3')
					// console.log(num1,'num1num1')
					// console.log(this.data.listId,'this.data.listIdthis.data.listId')
					if(this.data.listId.length == num3){
						wx.navigateTo({ url: '../good-payment/good-payment?id='+this.data.listId })
					}	
				}else{
					// console.log(111111111111)
					wx.showToast({
						title: '库存不足',
						icon: 'none'
					})
					return false
				}
				// wx.navigateTo({ url: '../good-payment/good-payment?id='+this.data.listId })		
			}else{
				num2++
				if(num2==shopcar.length){
					wx.showModal({
					    content: '您还未选择宝贝哦',
						showCancel: false,
					    confirmText: "确定",
					    success: function (res) {
					        if (res.confirm) {
					            // console.log('用户点击主操作')
					        }
					    }
					});
				}
				
			}
		
		}
	}else{
		wx.showToast({
		    title: '请绑定手机号码',
		    icon: 'none',
		    success: function () {
		      setTimeout(function() {
		        wx.navigateTo({
              url: '../comprehensivBind/comprehensivBind'
		        })
		      }, 1000);
		    }
		});
	}
	
		
},
// 去加入购物车
toGoodList(){
	wx.switchTab({
		url: '../home/home'
	})
},
//去登录
goLogin(){
	wx.switchTab({
		url: '../personal-center/personal-center'
	})
}

})
